import { Select } from 'antd';

const { Option } = Select;

// 下拉数据字典查询
export const DropDownSelect = (dict, type, mode = '', width, placeholder = "请选择", showSearch = false, disabled = false, onSelect) => (
  <Select
    showSearch={showSearch}
    mode={ mode }
    disabled={ disabled }
    style={{ width: width || '100%' }}
    placeholder={placeholder}
    allowClear
    onSelect={onSelect}
    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
  >
    { dict[type] ? getOption(dict[type]) : false }
  </Select>
);

export const DropDownSelectObj = ({ dict, onChange, type, mode = '', width = '100%', placeholder = "请选择", showSearch = null, disabled = false }) => (
  <Select
    showSearch={showSearch}
    mode={mode}
    disabled={disabled}
    style={{ width }}
    placeholder={placeholder}
    allowClear
    onChange={onChange}
    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
  >
    {dict[type] ? getOption(dict[type]) : null}
  </Select>
);

// 下拉列表查询
export const DropDownSelectList = (dict, mode = '', width, onSelect) => (
  <Select
    mode={ mode }
    style={{ width: width || '100%' }}
    placeholder="请选择"
    onSelect={onSelect}
    allowClear
  >
    { dict ? getOptionList(dict) : null }
  </Select>
);

function getOption(data) {
  const children = [];
  let { entries } = Object;
  for (let [key, value] of entries(data)) {
    children.push(<Option key={key}>{value}</Option>);
  }
  return children;
}

function getOptionList(data) {
  const children = [];
  if(Array.isArray(data)) {
    data.forEach((item) => {
      children.push(<Option key={item.id}>{item.name}</Option>);
    });
  }
  return children;
}
